package account

import (
	"C"
	"github.com/gin-gonic/gin"
	"moko/internal/request/parameter"
	"moko/internal/services/account"
	"net/http"
	"strconv"
)

func Register(c *gin.Context) {
	var params parameter.Register
	err := c.ShouldBindJSON(&params)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": http.StatusBadRequest, "msg": err.Error()})
		return
	}

	userLogin := &login.UserLogin{}
	if regRes := userLogin.Register(params); regRes.Code != http.StatusOK {
		c.JSON(http.StatusInternalServerError, gin.H{"code": regRes.Code, "msg": regRes.Msg})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": http.StatusOK, "msg": "注册成功"})
	return
}

func Login(c *gin.Context) {
	var params parameter.Login
	err := c.ShouldBindJSON(&params)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": http.StatusBadRequest, "msg": err.Error()})
		return
	}

	userLogin := &login.UserLogin{}
	regRes := userLogin.Login(params)
	if regRes.Code != http.StatusOK {
		c.JSON(http.StatusInternalServerError, gin.H{"code": regRes.Code, "msg": regRes.Msg})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": http.StatusOK, "msg": "登录成功", "data": regRes.Data})
	return
}

func Logout(c *gin.Context) {
	token := c.GetHeader("Authorization")
	userLogin := &login.UserLogin{}
	userLogin.Logout(token)

	c.JSON(http.StatusOK, gin.H{"code": http.StatusOK, "msg": "登录成功"})
}

func UserInfo(c *gin.Context) {
	userId, _ := strconv.ParseUint(c.Param("id"), 10, 0)
	if userId == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"code": http.StatusBadRequest, "msg": "缺少id参数"})
		return
	}
	userLogin := &login.UserLogin{}
	userInfo := userLogin.UserInfo(uint(userId))

	c.JSON(http.StatusOK, gin.H{"code": userInfo.Code, "msg": userInfo.Msg, "data": userInfo.Data})
	return
}
